//js和jsx的交互接口
var cs = new CSInterface();

/*
 * #htmlId.onclick( 'eventFunction(#htmlId1, #htmlId2)' ) 
 */
String.prototype.onclick = function(eventFunctionStr) {
    document.getElementById(this).addEventListener("click",function(){
        eventArgumentStr = replaceParamToArgument(eventFunctionStr)
        try { console.log(eventArgumentStr) } catch (error) { $.write(error) }
        
        try {
            cs.evalScript(eventArgumentStr);
        } catch (error) {}
    })
}

'btnCreate'.onclick('makePoster(width, width)')


/*
 *  "event('width', 'height')" => 'event(100, 200)'
 */
function replaceParamToArgument(eventStr) {
    if (eventStr.indexOf('(') < 0) {  return eventStr + '()' }

    var fnName = eventStr.substring(0, eventStr.indexOf('(') )
    var paramStr = '()'
    var params = eventStr.match( /\((.+)\)/g ) 
    var eventParams = eventStr.substring(eventStr.indexOf('(') + 1, eventStr.indexOf(')'))
    if (eventParams) {
        var params = eventParams.split(',')
        paramStr = genParamValueStr(params)
    }
    return  fnName + paramStr
}

/*
 * ['width', 'height'] => '(100, 200)'
 */
function genParamValueStr(params) {
    var paramStr = '('
    if (params && params.length) {
        var paramArr = []
        for (let i = 0; i < params.length; i++) {
            var prop = params[i].replace(/(^\s*)|(\s*$)/g, '')
            var propVal = document.getElementById(prop) && document.getElementById(prop).value;
            propVal && paramArr.push(propVal)
        } 
        paramStr = paramStr + paramArr.join(',')
    }
    paramStr += ')'
    return paramStr
}